const gulp = require("gulp");
const { watch, series } = require('gulp');
const browserify = require("browserify");
const source = require("vinyl-source-stream");
const watchify = require("watchify");
const tsify = require("tsify");
const fancy_log = require("fancy-log");
const sourcemaps = require("gulp-sourcemaps");
const buffer = require("vinyl-buffer");
const browserSync = require('browser-sync').create();

const paths = {
  pages: ["src/*.html"],
};

const watchedBrowserify = watchify(
    browserify({
      basedir: ".",
      debug: true,
      entries: ["src/main.ts"],
      cache: {},
      packageCache: {},
    }).plugin(tsify)
);

gulp.task("copy-html", function () {
  return gulp.src(paths.pages).pipe(gulp.dest("dist"));
});

gulp.task(
  "compile",
  gulp.series(gulp.parallel("copy-html"), function () {
    return browserify({
      basedir: ".",
      debug: true,
      entries: ["src/main.ts"],
      cache: {},
      packageCache: {},
    })
      .plugin(tsify)
      .transform("babelify", {
        presets: ["es2015"],
        extensions: [".ts"],
      })
      .bundle()
      .pipe(source("bundle.js"))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write("./"))
      .pipe(gulp.dest("dist"))
  })
);

function bundle() {
  return watchedBrowserify
    .bundle()
    .on("error", fancy_log)
    .pipe(source("bundle.js"))
    .pipe(gulp.dest("dist"));
}

// 开启服务器
gulp.task('serve', function() {
	browserSync.init({
		server:{
			baseDir:'./dist',
		},
		port: 3001
	});
	gulp.watch("src/**/*.ts").on('change', browserSync.reload);
})

gulp.task('default', series(gulp.parallel("compile"),'serve'));

// 观察 ts 文件变化，重新执行编译任务
watch('src/**/*.ts', series("compile"));

// 监听.ts变化
watchedBrowserify.on("update", bundle);

// 当文件更改是，打印日志
watchedBrowserify.on("log", fancy_log);